package org.vnl.platform.dk.util;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 
 * 基本型態的錯誤，可供日後使用I18n使用。
 * 
 * @author Vaughan
 *
 */
abstract public class PDKRuntimeException extends RuntimeException {

    /**
     * 
     */
    private static final long serialVersionUID = 6725624936664222919L;

    private static final String DEFAULT_UNKNOWN = "UNKNOWN";


    /**
     * 系統代碼，表示此錯誤由這個系統發出的
     */
    private String systemId;
    /**
     * 錯誤程度
     */
    private String severity;
    /**
     * 描述錯誤程式的參數
     */
    private Object[] parameters;

    public PDKRuntimeException() {
        this(DEFAULT_UNKNOWN, DEFAULT_UNKNOWN, DEFAULT_UNKNOWN, null, null);
    }

    public PDKRuntimeException(String systemId, String msg, String severity, Object[] parameters, Throwable cause) {
        super(msg, cause);
        this.severity = severity;
        this.systemId = systemId;
        this.parameters = parameters;
    }
    
    public String getSystemId() {
        return systemId;
    }

    public void setSystemId(String systemId) {
        this.systemId = systemId;
    }

    public String getSeverity() {
        return severity;
    }

    public void setSeverity(String severity) {
        this.severity = severity;
    }

    public Object[] getParameters() {
        return parameters;
    }

    public void setParameters(Object[] parameters) {
        this.parameters = parameters;
    }

    public String getLocalizedMessage(Locale locale) {
        if (locale == null) {
            return getDefaultLocalizedMessage(getDefaultBundleName());
        }
        return getRealLocalizedMessage(getDefaultBundleName(),locale);
    }

    abstract protected String getDefaultBundleName();
    
    private String formatMessage(String pattern) {
        return MessageFormat.format(pattern, getParameters());
    }

    private String getRealLocalizedMessage(String bundleName, Locale locale) {
        try {
            ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale, Thread.currentThread().getContextClassLoader());
            return formatMessage(bundle.getString(getMessage())); 
        } catch (Exception e) {
            return getDefaultLocalizedMessage(bundleName);
        }
    }

    private String getDefaultLocalizedMessage(String bundleName) {
        String message = ResourceBundle.getBundle(bundleName, null, Thread.currentThread().getContextClassLoader()).getString(getMessage());
        return formatMessage(message);
    }
}
